//
//  JJExtenUIImageView.swift
//  swiftProject
//
//  Created by yangjian on 2021/12/25.
//

import UIKit

extension UIImageView {
    
    func setGifImage(data : Data){
        let source = CGImageSourceCreateWithData(data as CFData, nil)
        guard let source = source else { return }
        let count = CGImageSourceGetCount(source)
        if count > 1 {
            var images = [UIImage].init()
            var duration : CGFloat = 0
            for i in 0 ..< count {
                let imageRef = CGImageSourceCreateImageAtIndex(source, i, nil)
                guard let imageRef = imageRef else {continue}
                images.append(UIImage.init(cgImage: imageRef, scale: UIScreen.main.scale, orientation: .up))
                duration += self.fetchGifDuration(imageRef: source, index: i)
            }
            if duration == 0 {
                duration = CGFloat(count) * 0.1
            }
            self.animationImages = images
            self.animationDuration = duration
            self.animationRepeatCount = 0
            RunLoop.current.perform(inModes: [RunLoop.Mode.common]) {
                self.startAnimating()
            }
        }else {
            self.image = UIImage.init(data: data)
        }
    }
    
    func fetchGifDuration(imageRef : CGImageSource,index:Int) -> CGFloat {
//        var duration = 0.1
        guard
            let properties = CGImageSourceCopyPropertiesAtIndex(imageRef, index, nil),
                let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
                let frameDuration = (gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber)
        else
        {
            return 0.1
        }
        return frameDuration.doubleValue
    }
}
